package com.zjg.db.utills;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

public class DBConnection {
	
	private static ThreadLocal<Connection> connections = new ThreadLocal<>();

	private static final String DRIVER;
	private static final String URL;
	private static final String USER;
	private static final String PASSWORD;
	static {
		Properties pre = new Properties();
		try {
			pre.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
		} catch (Exception e) {
			
		}
		DRIVER = pre.getProperty("jdbc.DRIVER");
		URL = pre.getProperty("jdbc.URL");
		USER = pre.getProperty("jdbc.USER");
		PASSWORD = pre.getProperty("jdbc.PASSWORD");
		try {
			Class.forName(DRIVER);

		} catch (Exception e) {

		}

	}

	public static Connection getConnection() {
		Connection connection = connections.get();
		try {
			if (connection == null || connection.isClosed()) {
				try {
					connection = DriverManager.getConnection(URL, USER, PASSWORD);
					connections.set(connection);
				} catch (SQLException e) {
					
				}
			}
		} catch (SQLException e) {

		}

		return connection;

	}

	public static void closeConnection(Connection connection) {
		if (connection != null) {
			try {
				connection.close();

			} catch (SQLException e) {
				
			}
		}
	}
}
